package com.vap_plugin.ultra.vap_plugin

import android.content.Context
import android.view.View
import com.tencent.qgame.animplayer.AnimConfig
import com.tencent.qgame.animplayer.AnimView
import com.tencent.qgame.animplayer.Constant
import com.tencent.qgame.animplayer.inter.IAnimListener
import com.tencent.qgame.animplayer.util.ScaleType
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView
import java.io.File

import com.tencent.qgame.animplayer.inter.IFetchResource
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.widget.Toast
import com.tencent.qgame.animplayer.mix.Resource
import com.tencent.qgame.animplayer.mix.Src
import com.tencent.qgame.animplayer.util.ScaleTypeCenterCrop
import com.tencent.qgame.animplayer.util.ScaleTypeFitCenter
import com.tencent.qgame.animplayer.util.ScaleTypeUtil
import java.util.*

internal class NativeVapView(
    private val  context: Context,
    private val binaryMessenger: BinaryMessenger,
    viewId: Int,
) : PlatformView, MethodChannel.MethodCallHandler {
    /**
     * vao 视频播放容器
     */
    private val vapView: AnimView = AnimView(context)

    /**
     * 方法调用的回调
     */
    var result: MethodChannel.Result? = null

    /**
     *通信通道
     */
    var methodChannel: MethodChannel? = null

    /**
    * 保存flutter传递过来的参数
    */
    private var argumentsMap: MutableMap<String, Any>? = mutableMapOf()

    init {
        /**
         * 居中播放
         */
        vapView.setScaleType(ScaleType.CENTER_CROP)
        vapView.setAnimListener(object : IAnimListener {
            override fun onFailed(errorType: Int, errorMsg: String?) {
                result?.success(mapOf("status" to "playFail","msg" to errorMsg))
            }

            override fun onVideoComplete() {
                val notDestroy = argumentsMap?.get("notDestroy") as? Boolean
                if (notDestroy != true) {
                    vapView.hide()
                }
                result?.success(mapOf("status" to "playEnd","msg" to ""))
            }

            override fun onVideoDestroy() {
                val notDestroy = argumentsMap?.get("notDestroy") as? Boolean
                if (notDestroy != true) {
                    vapView.hide()
                }
            }

            override fun onVideoRender(frameIndex: Int, config: AnimConfig?) {}

            override fun onVideoStart() {}

        })
        /**
         * 注册资源获取类
         */
        vapView.setFetchResource(object : IFetchResource {
            /**
             * 获取图片资源
             * 无论图片是否获取成功都必须回调 result 否则会无限等待资源
             */
            override fun fetchImage(resource: Resource, result: (Bitmap?) -> Unit) {
                /**
                 * srcTag是素材中的一个标记，在制作素材时定义
                 * 解析时由业务读取tag决定需要播放的内容是什么
                 * 比如：一个素材里需要显示多个头像，则需要定义多个不同的tag，表示不同位置，需要显示不同的头像，文字类似
                 */
                if(resource.type == Src.SrcType.IMG) {
                    val data  = argumentsMap?.get(resource.tag) as ByteArray
                    val options = BitmapFactory.Options()
//                  options.inPreferredConfig = Bitmap.Config.RGB_565
                    val bitmap = BitmapFactory.decodeByteArray(data, 0, data.size, options)
                    result(bitmap)
                } else {
                    result(null)
                }
            }

            /**
             * 获取文字资源
             */
            override fun fetchText(resource: Resource, result: (String?) -> Unit) {
                if(resource.type == Src.SrcType.TXT) {
                   val content = argumentsMap?.get(resource.tag) as String
                    if (content.isNotEmpty()) {
                        result(content)
                    }
                } else {
                    result(null)
                }
            }

            /**
             * 播放完毕后的资源回收
             */
            override fun releaseResource(resources: List<Resource>) {
                resources.forEach {
                    it.bitmap?.recycle()
                }
            }
        })
//
        // 创建通信渠道，用于 Flutter 调用原生控件的方法
        methodChannel =
            MethodChannel(this.binaryMessenger, "com.vap_plugin.ultra.FlutterView_$viewId")
        methodChannel?.setMethodCallHandler(this)
    }

    override fun getView(): View {
        return vapView;
    }

    override fun dispose() {
        /**
         * 释放资源
         */
        methodChannel?.setMethodCallHandler(null)
    }

    override fun onMethodCall(methodCall: MethodCall, result: MethodChannel.Result) {
        this.result = result
        when (methodCall.method) {
            "playPath" -> {
                this.argumentsMap = (methodCall.arguments as? MutableMap<String, Any>)

                val loop = (this.argumentsMap?.get("loopCount") as? String)?.toIntOrNull()
                if (loop != null) {
                    if (loop == -1) {
                        vapView.setLoop(Int.MAX_VALUE)
                    } else {
                        vapView.setLoop(loop)
                    }
                }

                val path = this.argumentsMap?.get("path") as? String
                if (path?.isNotEmpty() == true) {
                    val file = File(path)
                    vapView.startPlay(file)
                }
            }
            "playAsset" -> {
                this.argumentsMap = (methodCall.arguments as? MutableMap<String, Any>)

                val loop = (this.argumentsMap?.get("loopCount") as? String)?.toIntOrNull()
                if (loop != null) {
                    if (loop == -1) {
                        vapView.setLoop(Int.MAX_VALUE)
                    } else {
                        vapView.setLoop(loop)
                    }
                }

                val path = this.argumentsMap?.get("path") as? String
                    if (path?.isNotEmpty() == true) {
                        vapView.startPlay(context.assets, "flutter_assets/$path")
                    }
                }
            "stopPlay" -> {
                vapView.stopPlay()
            }

            "manualDestroy" -> {
                argumentsMap?.set("notDestroy", false)
                vapView.stopPlay()
                vapView.hide()
            }
        }
    }

}